package com.qx.cn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.cn.model.OrgInfo;
import com.qx.cn.model.User;
import com.qx.cn.service.OrgInfoService;
import com.qx.cn.service.UserService;
import com.qx.cn.tool.TreeNode;
import com.qx.cn.vo.OrgInfoVO;

@ParentPackage("netxzt")
@Namespace("/")
@InterceptorRefs({@InterceptorRef("content")})
@Results({@Result(name = "outlogin", location = "/admin!loseSession"), @Result(name = "getOutlogin", location = "/admin!otherlogin"),
    @Result(name = "orgList", location = "/WEB-INF/page/orgInfo/orgList.jsp")})
@Action(value = "org", interceptorRefs = {@InterceptorRef("loginedCheck")})
public class OrgInfoAction extends BaseAction
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = -2946500387047048504L;
    
    @Autowired
    private OrgInfoService orgInfoService;
    
    @Autowired
    private UserService userService;
    
    private String orgName;
    
    private Integer enabled;
    
    private String parCode;
    
    private String orgCode;
    
    private String orgDuty;
    
    private String orgMemo;
    
    private String id;
    
    private String userId;
    
    private String departCode;
    
    private Long isolistations;
    
    public String queryOrgTreeToUser()
    {
        String sta = "open";
        List<OrgInfo> orgInfos = orgInfoService.queryOrgListToUserByAsc(parCode);
        JSONArray jsonArray = new JSONArray();
        for (OrgInfo org : orgInfos)
        {
            JSONObject obj = new JSONObject();
            List<OrgInfo> sonOrgs = orgInfoService.queryOrgListByAsc(org.getOrgCode());
            if (sonOrgs.size() > 1)
            {
                sta = "closed";
            }
            else
            {
                sta = "open";
            }
            obj.put("state", sta);
            obj.put("id", org.getOrgCode());
            obj.put("text", org.getOrgName());
            jsonArray.add(obj);
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(jsonArray.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String queryGiveOrgToUser()
    {
        String sta = "open";
        List<OrgInfo> orgInfos = orgInfoService.queryOrgListToUserByAsc(parCode);
        JSONArray jsonArray = new JSONArray();
        for (OrgInfo org : orgInfos)
        {
            JSONObject obj = new JSONObject();
            List<OrgInfo> sonOrgs = orgInfoService.queryOrgListByAsc(org.getOrgCode());
            if (sonOrgs.size() > 1)
            {
                sta = "closed";
            }
            else
            {
                sta = "open";
            }
            obj.put("state", sta);
            obj.put("id", org.getOrgCode());
            obj.put("text", org.getOrgName());
            User user = userService.loadUserById(Long.valueOf(userId));
            if ((user.getOrgCodeAttach() != null) && (!"".equals(user.getOrgCodeAttach())))
            {
                String[] orgCode = user.getOrgCodeAttach().split(",");
                for (int i = 0; i < orgCode.length; i++)
                {
                    if (orgCode[i].equals(org.getOrgCode()))
                    {
                        obj.put("checked", Boolean.valueOf(true));
                    }
                }
            }
            jsonArray.add(obj);
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(jsonArray.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String orgList()
    {
        return "orgList";
    }
    
    public String queryOrgList()
    {
        OrgInfo org = new OrgInfo();
        org.setOrgCode(id);
        List<OrgInfoVO> orgInfos = orgInfoService.queryOrgListTreeGrid(org);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSON(orgInfos));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loadGrgList()
    {
        JSONArray arrJson = new JSONArray();
        List<OrgInfo> orgInfos = orgInfoService.queryOrgList();
        for (OrgInfo orgInfo : orgInfos)
        {
            JSONObject json = new JSONObject();
            if (!orgInfo.getOrgCode().equals("1"))
            {
                json.put("text", orgInfo.getOrgName());
                json.put("id", orgInfo.getOrgCode());
                arrJson.add(json);
            }
        }
        JSONObject obj = new JSONObject();
        obj.put("children", arrJson);
        obj.put("id", 1);
        obj.put("text", "根节点");
        try
        {
            PrintWriter out = response.getWriter();
            out.print("[" + obj.toString() + "]");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveOrgByPar()
    {
        JSONObject object = new JSONObject();
        if (!"".equals(orgCode))
        {
            OrgInfo orgInfo = orgInfoService.loadOrgListBydepartCode(departCode);
            if (orgInfo != null)
            {
                if (orgCode.equals(orgInfo.getOrgCode()))
                {
                    List<OrgInfo> orgSizeInfos = orgInfoService.queryOrgListToUserByAsc(orgCode);
                    String pCode = orgCode.substring(0, orgCode.length() - 3);
                    if ((orgSizeInfos.size() > 0) && (!pCode.equals(parCode)))
                    {
                        object.put("result", 2);
                        object.put("errorMsg", "该组织机构有下属机构不可以修改上级节点!");
                    }
                    else
                    {
                        OrgInfo reOrg = orgInfoService.loadOrgByCode(orgCode);
                        List<OrgInfo> orgInfos = orgInfoService.queryOrgListByAsc(parCode);
                        reOrg.setOrgName(orgName);
                        reOrg.setEnabled(enabled);
                        reOrg.setOrgDuty(orgDuty);
                        reOrg.setMemo(orgMemo);
                        if (orgInfos.size() == 1)
                        {
                            reOrg.setOrgCode(parCode + "001");
                        }
                        else if (!pCode.equals(parCode))
                        {
                            if ("1".equals(parCode))
                            {
                                List<OrgInfo> orgInfos2 = orgInfoService.queryOrgListToUserByAsc("1");
                                StringBuffer codeBuf = new StringBuffer();
                                String codeStr = ((OrgInfo)orgInfos2.get(orgInfos2.size() - 1)).getOrgCode();
                                String startCodeStr = codeStr.substring(0, codeStr.length() - 4);
                                String endCodeStr = codeStr.substring(codeStr.length() - 4, codeStr.length());
                                Integer endCodeInt = Integer.valueOf(Integer.valueOf(endCodeStr).intValue() + 1);
                                codeBuf.append(startCodeStr).append(endCodeInt);
                                reOrg.setOrgCode(codeBuf.toString());
                            }
                            else
                            {
                                StringBuffer codeBuf = new StringBuffer();
                                String codeStr = ((OrgInfo)orgInfos.get(orgInfos.size() - 1)).getOrgCode();
                                String startCodeStr = codeStr.substring(0, codeStr.length() - 4);
                                String endCodeStr = codeStr.substring(codeStr.length() - 4, codeStr.length());
                                String endCodeInt = String.valueOf(Integer.valueOf(endCodeStr).intValue() + 1);
                                String endStr = "";
                                if (endCodeInt.length() == 1)
                                {
                                    endStr = "000" + endCodeInt;
                                }
                                else if (endCodeInt.length() == 2)
                                {
                                    endStr = "00" + endCodeInt;
                                }
                                else if (endCodeInt.length() == 3)
                                {
                                    endStr = "0" + endCodeInt;
                                }
                                else if (endCodeInt.length() == 4)
                                {
                                    endStr = endCodeInt;
                                }
                                codeBuf.append(startCodeStr).append(endStr);
                                reOrg.setOrgCode(codeBuf.toString());
                            }
                        }
                        else
                        {
                            reOrg.setOrgCode(orgCode);
                        }
                        
                        userService.updateUserByChangeOrg(orgCode, reOrg.getOrgCode());
                        orgInfoService.saveOrgInfo(reOrg);
                        object.put("result", 1);
                    }
                }
                else
                {
                    object.put("result", Integer.valueOf(3));
                    object.put("errorMsg", "该部门代号已经存在!");
                }
            }
            else
            
            {
                List<OrgInfo> orgSizeInfos = orgInfoService.queryOrgListToUserByAsc(orgCode);
                String pCode = orgCode.substring(0, orgCode.length() - 3);
                if ((orgSizeInfos.size() > 0) && (!pCode.equals(parCode)))
                {
                    object.put("result", 2);
                    object.put("errorMsg", "该组织机构有下属机构不可以修改上级节点!");
                }
                else
                {
                    OrgInfo reOrg = orgInfoService.loadOrgByCode(orgCode);
                    List<OrgInfo> orgInfos = orgInfoService.queryOrgListByAsc(parCode);
                    reOrg.setOrgName(orgName);
                    reOrg.setEnabled(enabled);
                    reOrg.setOrgDuty(orgDuty);
                    reOrg.setMemo(orgMemo);
                    if (orgInfos.size() == 1)
                    {
                        reOrg.setOrgCode(parCode + "001");
                    }
                    else if (!pCode.equals(parCode))
                    {
                        if ("1".equals(parCode))
                        {
                            List<OrgInfo> orgInfos2 = orgInfoService.queryOrgListToUserByAsc("1");
                            StringBuffer codeBuf = new StringBuffer();
                            String codeStr = ((OrgInfo)orgInfos2.get(orgInfos2.size() - 1)).getOrgCode();
                            String startCodeStr = codeStr.substring(0, codeStr.length() - 4);
                            String endCodeStr = codeStr.substring(codeStr.length() - 4, codeStr.length());
                            String endCodeInt = String.valueOf(Integer.valueOf(endCodeStr).intValue() + 1);
                            String endStr = "";
                            if (endCodeInt.length() == 1)
                            {
                                endStr = "000" + endCodeInt;
                            }
                            else if (endCodeInt.length() == 2)
                            {
                                endStr = "00" + endCodeInt;
                            }
                            else if (endCodeInt.length() == 3)
                            {
                                endStr = "0" + endCodeInt;
                            }
                            else if (endCodeInt.length() == 4)
                            {
                                endStr = endCodeInt;
                            }
                            codeBuf.append(startCodeStr).append(endStr);
                            reOrg.setOrgCode(codeBuf.toString());
                        }
                        else
                        {
                            StringBuffer codeBuf = new StringBuffer();
                            List<OrgInfo> orgInfos2 = orgInfoService.queryOrgListToUserByAsc(parCode);
                            String codeStr = ((OrgInfo)orgInfos2.get(orgInfos2.size() - 1)).getOrgCode();
                            String startCodeStr = codeStr.substring(0, codeStr.length() - 4);
                            String endCodeStr = codeStr.substring(codeStr.length() - 4, codeStr.length());
                            String endCodeInt = String.valueOf(Integer.valueOf(endCodeStr).intValue() + 1);
                            String endStr = "";
                            if (endCodeInt.length() == 1)
                            {
                                endStr = "000" + endCodeInt;
                            }
                            else if (endCodeInt.length() == 2)
                            {
                                endStr = "00" + endCodeInt;
                            }
                            else if (endCodeInt.length() == 3)
                            {
                                endStr = "0" + endCodeInt;
                            }
                            else if (endCodeInt.length() == 4)
                            {
                                endStr = endCodeInt;
                            }
                            codeBuf.append(startCodeStr).append(endStr);
                            reOrg.setOrgCode(codeBuf.toString());
                        }
                    }
                    else
                    {
                        reOrg.setOrgCode(orgCode);
                    }
                    userService.updateUserByChangeOrg(orgCode, reOrg.getOrgCode());
                    orgInfoService.saveOrgInfo(reOrg);
                    object.put("result", 1);
                }
            }
        }
        else
        {
            
            List<OrgInfo> orgInfoIsCodes = orgInfoService.queryAllOrgListBydepartCode(departCode);
            if (orgInfoIsCodes.size() > 0)
            {
                object.put("result", Integer.valueOf(3));
                object.put("errorMsg", "该部门代号已经存在!");
            }
            else
            {
                OrgInfo org = new OrgInfo();
                org.setOrgName(orgName);
                List<OrgInfo> orgInfos = orgInfoService.queryOrgListByAsc(parCode);
                if (orgInfos.size() == 1)
                {
                    org.setOrgCode(parCode + "001");
                }
                else if ("1".equals(parCode))
                {
                    List<OrgInfo> orgInfos2 = orgInfoService.queryOrgListToUserByAsc("1");
                    StringBuffer codeBuf = new StringBuffer();
                    String codeStr = ((OrgInfo)orgInfos2.get(orgInfos2.size() - 1)).getOrgCode();
                    String startCodeStr = codeStr.substring(0, codeStr.length() - 4);
                    String endCodeStr = codeStr.substring(codeStr.length() - 4, codeStr.length());
                    String endCodeInt = String.valueOf(Integer.valueOf(endCodeStr).intValue() + 1);
                    String endStr = "";
                    if (endCodeInt.length() == 1)
                    {
                        endStr = "000" + endCodeInt;
                    }
                    else if (endCodeInt.length() == 2)
                    {
                        endStr = "00" + endCodeInt;
                    }
                    else if (endCodeInt.length() == 3)
                    {
                        endStr = "0" + endCodeInt;
                    }
                    else if (endCodeInt.length() == 4)
                    {
                        endStr = endCodeInt;
                    }
                    codeBuf.append(startCodeStr).append(endStr);
                    org.setOrgCode(codeBuf.toString());
                }
                else
                {
                    List<OrgInfo> orgOneSonInfos = orgInfoService.queryOrgListToUserByAsc(parCode);
                    StringBuffer codeBuf = new StringBuffer();
                    String codeStr = ((OrgInfo)orgOneSonInfos.get(orgOneSonInfos.size() - 1)).getOrgCode();
                    String startCodeStr = codeStr.substring(0, codeStr.length() - 4);
                    String endCodeStr = codeStr.substring(codeStr.length() - 4, codeStr.length());
                    String endCodeInt = String.valueOf(Integer.valueOf(endCodeStr).intValue() + 1);
                    String endStr = "";
                    if (endCodeInt.length() == 1)
                    {
                        endStr = "000" + endCodeInt;
                    }
                    else if (endCodeInt.length() == 2)
                    {
                        endStr = "00" + endCodeInt;
                    }
                    else if (endCodeInt.length() == 3)
                    {
                        endStr = "0" + endCodeInt;
                    }
                    else if (endCodeInt.length() == 4)
                    {
                        endStr = endCodeInt;
                    }
                    codeBuf.append(startCodeStr).append(endStr);
                    org.setOrgCode(codeBuf.toString());
                }
                
                org.setOrgDuty(orgDuty);
                org.setMemo(orgMemo);
                org.setEnabled(enabled);
                orgInfoService.saveOrgInfo(org);
                object.put("result", 1);
            }
            
        }
        
        try
        {
            
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String deleteOrgInfo()
    {
        List<User> users = userService.queryUserByLikeCode(orgCode);
        JSONObject object = new JSONObject();
        if (users.size() > 0)
        {
            object.put("result", Integer.valueOf(3));
            object.put("errorMsg", "该组织机构或者子机构下有成员,不可删除!");
        }
        else
        {
            List<OrgInfo> orgInfos = orgInfoService.queryOrgListByAsc(orgCode);
            boolean flag = orgInfoService.deleteOrgListByCode(orgCode);
            JSONArray arrJson = new JSONArray();
            if (flag)
            {
                object.put("result", 1);
                object.put("errorMsg", "删除组织机构成功!");
                for (OrgInfo orgInfo : orgInfos)
                {
                    JSONObject json = new JSONObject();
                    json.put("orgCode", orgInfo.getOrgCode());
                    arrJson.add(json);
                }
                object.put("datas", arrJson);
            }
            else
            {
                object.put("result", 2);
                object.put("errorMsg", "删除组织机构失败!");
            }
            
        }
        
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String queryOrgComTree()
    {
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setOrgCode(orgCode);
        List<TreeNode> treeNodes = orgInfoService.queryComTree(orgInfo, true);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(treeNodes));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String getJson()
    {
        List<Map<String, String>> menus = new ArrayList<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        response.setContentType("application/json");
        List<OrgInfo> orgInfos = orgInfoService.queryOrgList();
        for (OrgInfo o : orgInfos)
        {
            map.put("orgName", o.getOrgName());
            menus.add(map);
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSONString(menus));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loadOrgInfoByCode()
    {
        OrgInfo orgInfo = orgInfoService.loadOrgByCode(orgCode);
        JSONObject object = new JSONObject();
        object.put("orgCode", orgInfo.getOrgCode());
        object.put("orgName", orgInfo.getOrgName());
        object.put("parCode", orgInfo.getOrgCode().substring(0, orgInfo.getOrgCode().length() - 3));
        object.put("enabled", orgInfo.getEnabled());
        object.put("orgDuty", orgInfo.getOrgDuty());
        object.put("orgMemo", orgInfo.getMemo());
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String loadAddOrgInfoByCode()
    {
        JSONObject object = new JSONObject();
        if ((!"".equals(orgCode)) && (orgCode != null))
        {
            object.put("parCode", orgCode);
        }
        else
        {
            object.put("parCode", 1);
        }
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String saveLeaderToOrg()
    {
        OrgInfo orgInfo = orgInfoService.loadOrgByCode(orgCode);
        if ("".equals(userId))
        {
            orgInfo.setOrgLeader(null);
            orgInfoService.saveOrgInfo(orgInfo);
        }
        else
        {
            orgInfo.setOrgLeader(Long.valueOf(userId.trim()));
            orgInfoService.saveOrgInfo(orgInfo);
        }
        
        JSONObject object = new JSONObject();
        object.put("result", 1);
        try
        {
            PrintWriter out = response.getWriter();
            out.print(object.toString());
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    public String getOrgName()
    {
        return orgName;
    }
    
    public void setOrgName(String orgName)
    {
        this.orgName = orgName;
    }
    
    public Integer getEnabled()
    {
        return enabled;
    }
    
    public void setEnabled(Integer enabled)
    {
        this.enabled = enabled;
    }
    
    public String getParCode()
    {
        return parCode;
    }
    
    public void setParCode(String parCode)
    {
        this.parCode = parCode;
    }
    
    public String getOrgDuty()
    {
        return orgDuty;
    }
    
    public void setOrgDuty(String orgDuty)
    {
        this.orgDuty = orgDuty;
    }
    
    public String getOrgMemo()
    {
        return orgMemo;
    }
    
    public void setOrgMemo(String orgMemo)
    {
        this.orgMemo = orgMemo;
    }
    
    public String getId()
    {
        return id;
    }
    
    public void setId(String id)
    {
        this.id = id;
    }
    
    public String getOrgCode()
    {
        return orgCode;
    }
    
    public void setOrgCode(String orgCode)
    {
        this.orgCode = orgCode;
    }
    
    public String getUserId()
    {
        return userId;
    }
    
    public void setUserId(String userId)
    {
        this.userId = userId;
    }
    
    public String getDepartCode()
    {
        return departCode;
    }
    
    public void setDepartCode(String departCode)
    {
        this.departCode = departCode;
    }
    
    public Long getIsolistations()
    {
        return isolistations;
    }
    
    public void setIsolistations(Long isolistations)
    {
        this.isolistations = isolistations;
    }
}